<?php
/**
 * Descript:
 * User: lufeng501206@gmail.com
 * Date: 2017/3/7 23:11
 */

namespace App\Http\Controllers\Home;


use App\Http\Controllers\Controller;
use App\Models\Home\User;
use App\Models\LoginLogs;
use App\Models\MessagesReader;
use App\Repositories\AliRepos;
use App\Repositories\TasksRepos;
use App\Repositories\UsersRepos;
use Symfony\Component\HttpFoundation\Request;

class UserController extends Controller
{
    private $aliRepos = null;
    private $tasksRepos = null;
    private $usersRepos = null;
    private $userId;

    public function __construct(AliRepos $aliRepos, TasksRepos $tasksRepos, UsersRepos $usersRepos)
    {
        $this->middleware('verify.auth',['except' => 'getWechatUserInfo']);
        $this->tasksRepos = $tasksRepos;
        $this->aliRepos = $aliRepos;
        $this->usersRepos = $usersRepos;
    }


    /**
     * 重装密码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse\
     */
    public function modifyPassword(Request $request)
    {
        $inputs = $request->input();
        $mobile = $request->session()->get('login_user');
        $userModel = User::whereAccount($mobile)->first();
        if (!empty($inputs['oldPassword']) && password_verify($inputs['oldPassword'], $userModel->password)) {
            $userModel->password = password_hash($inputs['newPassword'], PASSWORD_DEFAULT);
            return successJson([], '密码重置成功');
        } else {
            return errorJson([], '旧密码错误');
        }
    }

    /**
     * 修改用户信息
     * @param Request $request
     */
    public function modifyUserInfo(Request $request)
    {
        $inputs = $request->input();
        $mobile = $request->session()->get('login_user');
        $userModel = User::whereAccount($mobile)->first();
        if (!empty($inputs['password'])) {
            $userModel->password = password_hash($inputs['password'], PASSWORD_DEFAULT);
        }
        if (!empty($inputs['name'])) {
            $userModel->name = $inputs['name'];
        }
        if (!empty($inputs['sex'])) {
            $userModel->sex = $inputs['sex'];
        }
        if (!empty($inputs['age'])) {
            $userModel->age = $inputs['age'];
        }
        if (!empty($inputs['identity'])) {
            $userModel->identity = $inputs['identity'];
        }
        if (!empty($inputs['province'])) {
            $userModel->province = $inputs['province'];
        }
        if (!empty($inputs['city'])) {
            $userModel->city = $inputs['city'];
        }
        $res = $userModel->save();
        if ($res) {
            return successJson();
        } else {
            return errorJson();
        }
    }

    /**
     * 获取结算总额
     *
     * @param $userId
     * @return int
     *
     */
    private function getTransformCashMoney($userId)
    {
            $conditions['state'] = 4;
            // 获取完成任务
            $userTaskLists = $this->tasksRepos->getTasksListsByUserId($userId,$conditions);
            // 获取提成任务
            $recommendUserTaskLists = [];
            // 获取好友列表
            $userInfo = $this->usersRepos->getUserInfo($userId);
            $recommendUserLists = $this->usersRepos->getRecommendUserLists($userInfo['account']);
            if (!empty($recommendUserLists) && is_array($recommendUserLists)) {
                foreach ($recommendUserLists as $key => $value) {
                    $lists = $this->tasksRepos->getTasksListsByUserId($value['id'],$conditions);
                    $recommendUserTaskLists = array_merge($recommendUserTaskLists,$lists);
                }
            }
            // 汇总数据
            $allTaskLists = array_merge($userTaskLists,$recommendUserTaskLists);
            // 返回数据
            $money = 0;
            if (!empty($allTaskLists) && is_array($allTaskLists)) {
                foreach ($allTaskLists as $key => $value) {
                    if ($value['user_id'] == $userId) {
                        $money += $value['money'];
                    } else {
                        $money += $value['rebate'];
                    }
                }
            }
            return $money;
    }

    /**
     * 获取用户概况
     * @return \Illuminate\Http\JsonResponse\
     */
    public function getUserInfo(Request $request)
    {
        $id = $this->usersRepos->getLoginUserId();
        $detail = $this->usersRepos->getUserDetailInfo($id);
        // 获取微信信息
        if ($this->isWeixin()) {
            $userWechatInfo = $request->session()->get('wechat_userinfo');
            $userWechatInfo = @json_decode($userWechatInfo, true);
            $detail['wechat_nickname'] = $userWechatInfo['nickname'];
            $detail['wechat_name'] = $userWechatInfo['name'];
            $detail['wechat_avatar'] = $userWechatInfo['avatars'];
        }
        $detail['transform_cash'] = $this->getTransformCashMoney($id);
        $data['detail'] = $detail;
        $data['identity'] = config('jinbell.identity');
        return successJson($data);
    }

    /**
     * 判断微信客户端
     * @return bool
     */
    public function isWeixin()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }
        return false;
    }

    public function getWechatUserInfo(Request $request)
    {
        $userWechatInfo = $request->session()->get('wechat_userinfo');
        $userWechatInfo = @json_decode($userWechatInfo, true);
        return successJson($userWechatInfo);
    }

    /**
     * 上传头像
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse\
     */
    public function uploadAvatar(Request $request)
    {
        $files = $request->file('avatar');
        $relatedPath = 'avatars/' . session('login_user');
        $path = $files->store($relatedPath);
        $userId = $this->usersRepos->getLoginUserId();
        $userModel = User::FindOrFail($userId);
        if (!empty($userModel)) {
            $userModel->avatars = env('STATIC_URL').$path;
            $userModel->save();
        }
        return successJson($path);
    }


    /**
     * 获取好友列表
     * @param $id
     * @return \Illuminate\Http\JsonResponse\
     */
    public function getFriendLists(Request $request)
    {
        $userId = $this->usersRepos->getLoginUserId();
        $userInfo = $this->usersRepos->getUserInfo($userId);
        $lists = $this->usersRepos->getFriendLists($userInfo['account']);
        $data['lists'] = rebulidDataIndex($lists);
        return successJson($data);
    }

    /**
     * 获取好友的任务列表
     * @param $id
     * @return \Illuminate\Http\JsonResponse\
     */
    public function getFriendTasks(Request $request)
    {
        $conditions = $inputs = $request->input();
        $userId = $this->usersRepos->getLoginUserId();
        $userInfo = $this->usersRepos->getUserInfo($userId);
        $userlists = $this->usersRepos->getFriendLists($userInfo['account']);
        $lists = [];
        if (!empty($userlists)) {
            foreach ($userlists as $key => $value) {
                $lists[] = $this->tasksRepos->getTasksListsByUserId($value['id'], $conditions);
            }
        }
//        $lists = $this->tasksRepos->getTasksListsByUserId($id, $conditions);
        return successJson($lists);
    }

    /**
     * 获取消息列表
     * @return \Illuminate\Http\JsonResponse\
     */
    public function getMessagesLists(Request $request)
    {
        $conditions = $inputs = $request->input();
        $userId = $this->usersRepos->getLoginUserId();
        $lists = $this->usersRepos->getMessagesLists($userId,$conditions);
        return successJson($lists);
    }

    /**
     * 获取消息详情信息
     * @param $id
     * @return \Illuminate\Http\JsonResponse\
     */
    public function getMessagesDetail($id)
    {
        $conditions['id'] = $id;
        $userId = $this->usersRepos->getLoginUserId();
        $lists = $this->usersRepos->getMessagesLists($userId,$conditions);
        return successJson($lists);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse\
     */
    public function changeMsgState(Request $request)
    {
        $inputs = $request->input();
        $messageId = $inputs['message_id'];
        $readState = $inputs['read_state'];
        $userId = $this->usersRepos->getLoginUserId();
        $readModel = MessagesReader::where('user_id', $userId)
            ->where('message_id', $messageId)->first();
        $readModel->read_state = $readState;
        $res = $readModel->save();
        if ($res) {
            return successJson();
        } else {
            return errorJson();
        }
    }

    /**
     * 接受邀请
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse\
     */
    public function bindRecommendUser(Request $request)
    {
        $RecommendUser = $request->input('recommend_user');
        $userId = $this->usersRepos->getLoginUserId();
        $userModel = User::FindOrFail($userId);
        if (!empty($userModel->recommend_user)) {
            return successJson('您已接受过推荐');
        }else{
            if ($RecommendUser == $userModel->account) {
                return successJson('推荐人不能接受推荐');
            }
            $userModel->recommend_user = $RecommendUser;
            $userModel->save();
            return successJson('接受推荐成功');
        }
    }

    /**
     * 获取用户概况
     * @return \Illuminate\Http\JsonResponse\
     */
    public function getUserInfoByAccount(Request $request)
    {
        $account = $request->input('account');
        $info = $this->usersRepos->getUserInfoByAccount($account);
        $id = $info['id'];
        $detail = $this->usersRepos->getUserDetailInfo($id);
        // 获取微信信息
        if ($this->isWeixin()) {
            $userWechatInfo = $request->session()->get('wechat_userinfo');
            $userWechatInfo = @json_decode($userWechatInfo, true);
            $detail['wechat_nickname'] = $userWechatInfo['nickname'];
            $detail['wechat_name'] = $userWechatInfo['name'];
            $detail['wechat_avatar'] = $userWechatInfo['avatars'];
        }
        $data['detail'] = $detail;
        $data['identity'] = config('jinbell.identity');
        return successJson($data);
    }
}